package com.lin.eventbus.context

import com.lin.eventbus.EventContext
import com.lin.eventbus.EventFuture
import com.lin.eventbus.concurrent.IFuture
import com.lin.eventbus.concurrent.IFutureImpl

class EventFutureImpl : IFutureImpl<EventContext>(),
    EventFuture {

    private var context: EventContextImpl? = null

    override fun bypassExecutionException(): Boolean {
        return true
    }

    override fun complete(result: EventContext?): IFuture<EventContext> {
        val context = result as EventContextImpl
        this.context = context
        if (context.isSuccess) {
            return super.complete(result)
        }
        if (!context.event.isRaiseException) {
            return super.complete(result)
        }
        var error: com.lin.eventbus.exception.EventBusException? = null
        context.throwExceptionIfNecessary()?.run {
            error = this
        }
        return super.complete(result, error)
    }

    override fun addDiscardListener(action: com.lin.eventbus.function.Block1<EventContext>) {
        addListener {
            context?.run {
                if (this.isDiscard) {
                    action.apply(this)
                }
            }
        }
    }
}
